package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.StgyException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.lease.model.entity.LeaseTerm;
import com.atguigu.lease.web.admin.service.LeaseTermService;
import com.atguigu.lease.web.admin.mapper.LeaseTermMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author gqs
 * @description 针对表【lease_term(租期)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class LeaseTermServiceImpl extends ServiceImpl<LeaseTermMapper, LeaseTerm>
    implements LeaseTermService {
  @Override
  public boolean saveOrUpdateTerm(LeaseTerm leaseTerm) {
    // 校验 租期名称和租期单位的组合唯一 例：1月
    Long id = leaseTerm.getId() == null ? -1 : leaseTerm.getId();
    // 根据租期名称和租期单位查询数据
    LeaseTerm dbLeaseTerm =
        this.getOne(
            Wrappers.lambdaQuery(LeaseTerm.class)
                .eq(LeaseTerm::getMonthCount, leaseTerm.getMonthCount())
                .eq(LeaseTerm::getUnit, leaseTerm.getUnit())
                .last("limit 1"));

    // 查询到数据为空或当前数据id与查询到的数据id相同，则更新数据 否则返回错误信息
    if ((dbLeaseTerm != null && !id.equals(dbLeaseTerm.getId()))) {
      throw new StgyException(ResultCodeEnum.LEASE_TERM_EXISTS_ERROR);
    }
    return this.saveOrUpdate(leaseTerm);
  }
}
